/*
 * @Description: 档案类型-层级 列表导航
 * @Author: Rfan
 * @Date: 2022-02-09 17:58:25
 * @LastEditTime: 2023-02-25 20:01:07
 */

import { useEffect, useState } from 'react';
import { Menu } from 'antd';
import { fetchATListByFondId } from '@/api/archivesType';
import { selectItemByKey } from '@/utils/list';
import { IArchiveType, ILevel } from '@/interfaces/archiveType';
// import classNames from 'classnames/bind';

// import styles from './index.module.scss';
// const cx = classNames.bind(styles);

const { SubMenu } = Menu;

const ATLevelNav = (props: any) => {
  const { activeFond, hideLowest, hideHighest, type = 1, onChange } = props;
  // 档案类型列表
  const [ATList, setATList] = useState([]);
  // 打开的一级菜单
  const [openKeys, setOpenKeys] = useState([]);
  // 打开的一级菜单
  const [selectKeys, setSelectKeys] = useState([]);
  // 打开的一级菜单历史记录
  const [openKeysHis, setOpenKeysHis] = useState([]);
  // 维护一级菜单的key
  const [rootSubmenuKeys, setRootSubmenuKeys] = useState<(string | undefined)[]>([]);

  useEffect(() => {
    if (activeFond) {
      setOpenKeys([]);
      fetchATListByFondId(activeFond, type).then((res: any) => {
        const { data } = res;

        setATList(data);
        if (data && data.length > 0) {
          const firstAt = data[0];
          if (firstAt && firstAt.levelList.length > 0) {
            if (hideHighest) {
              setSelectKeys([`${firstAt.id}-${firstAt.levelList[1].level}`]);
              onSelect({ key: `${firstAt.id}-${firstAt.levelList[1].level}`, atList: data });
              onOpenChange([`${firstAt.id}`]);
            } else {
              setSelectKeys([`${firstAt.id}-${firstAt.levelList[0].level}`]);
              onSelect({ key: `${firstAt.id}-${firstAt.levelList[0].level}`, atList: data });
              onOpenChange([`${firstAt.id}`]);
            }
          }
        }
      });
    }
  }, [activeFond]);

  /**
   * 获取到档案类型后设置一级菜单key
   */
  useEffect(() => {
    if (ATList.length > 0) {
      setOpenKeysHis([]);
      setRootSubmenuKeys(ATList.map((item) => `${item.id}`));
    }
  }, [ATList]);

  const onOpenChange = (keys: string[]) => {
    const latestOpenKey = keys.find((key: string) => openKeys.indexOf(key) === -1);
    const isOpened = openKeysHis.indexOf(latestOpenKey) >= 0;
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys);
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
    if (latestOpenKey && !isOpened) {
      setOpenKeysHis((state) => [...state, latestOpenKey]);
    }
  };

  const onSelect = ({ key, atList }: { key: string; atList?: IArchiveType[] }): void => {
    setSelectKeys([key]);
    const _list = ATList.length <= 0 ? atList : ATList;
    const [atId, levelId] = key.split('-');
    const atItem: any = selectItemByKey(parseInt(atId, 10), _list);
    const levelItem = selectItemByKey(parseInt(levelId, 10), atItem?.levelList || [], 'level');
    onChange({ atId, atItem, levelId, levelItem });
  };

  return (
    <>
      {ATList.length > 0 && (
        <Menu
          mode="inline"
          openKeys={openKeys}
          selectedKeys={selectKeys}
          onOpenChange={onOpenChange}
          onSelect={onSelect}
          style={{ width: 200 }}
        >
          {ATList.map((atItem: any) => (
            <SubMenu key={atItem.id} title={atItem.atName}>
              {atItem.levelList && hideLowest
                ? atItem.levelList
                    .filter((item: ILevel) => item.level > 0)
                    .map((item: any) => (
                      <Menu.Item key={`${atItem.id}-${item.level}`}>{item.levelName}</Menu.Item>
                    ))
                : hideHighest
                ? atItem.levelList
                    .filter((item: ILevel) => item.levelNum > 1)
                    .map((item: any) => (
                      <Menu.Item key={`${atItem.id}-${item.level}`}>{item.levelName}</Menu.Item>
                    ))
                : atItem.levelList.map((item: any) => (
                    <Menu.Item key={`${atItem.id}-${item.level}`}>{item.levelName}</Menu.Item>
                  ))}
            </SubMenu>
          ))}
        </Menu>
      )}
    </>
  );
};

export default ATLevelNav;
